package com.now.printer.ui.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;

import com.now.printer.R;
import com.now.printer.adapter.HtmlCollectAdapter;
import com.now.printer.base.BaseActivity2;
import com.now.printer.db.HtmlCollectTable;
import com.now.printer.utils.DbUtils;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.ViewHolder;

import org.xutils.DbManager;
import org.xutils.common.util.DensityUtil;
import org.xutils.common.util.LogUtil;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

public class HtmlPrintActivity extends BaseActivity2 {

    private GridView gridView;
    private String[] htmlCollect = new String[]{"惠普打印机设置"};
//    private int[] htmlIcon = new int[R.mipmap.];

    private String[] htmlUrl = new String[]{"192.168.223.1"};
    private List<HtmlCollectTable> totalList = new ArrayList<>();

    private static final String tempValue = "增加";
    private HtmlCollectAdapter htmlCollectAdapter;
    private EditText et_url;

    @Override
    public void doBusiness(Context mContext) {
        gridView = findViewById(R.id.gridView);
        et_url = findViewById(R.id.et_url);
        et_url.setOnEditorActionListener(onEditorActionListener);

        htmlCollectAdapter = new HtmlCollectAdapter(this, totalList);
        gridView.setAdapter(htmlCollectAdapter);

        try {
            DbManager db = x.getDb(DbUtils.daoConfig);

            List<HtmlCollectTable> selectList = db.selector(HtmlCollectTable.class).findAll();

            if (selectList == null) {
                List<HtmlCollectTable> htmlCollectTableList = new ArrayList<>();

                for (int i = 0; i < htmlCollect.length; i++) {
                    HtmlCollectTable htmlCollectBean = new HtmlCollectTable();
                    htmlCollectBean.setHtmlName(htmlCollect[i]);
                    htmlCollectBean.setHtmlUrl(htmlUrl[i]);
                    htmlCollectTableList.add(htmlCollectBean);
                }
                db.saveOrUpdate(htmlCollectTableList);

                //增加
                htmlCollectTableList.add(setDefaultAdd());
                totalList.addAll(htmlCollectTableList);

            } else {
                //增加
                selectList.add(setDefaultAdd());
                totalList.addAll(selectList);
            }

            LogUtil.i("total list size is : " + totalList.toString());
            htmlCollectAdapter.notifyDataSetChanged();

        } catch (DbException e) {
            e.printStackTrace();
        }

        gridView.setOnItemClickListener((parent, view, position, id) -> {
            if (!totalList.get(position).getHtmlName().equals(tempValue)) {
                Intent intent = new Intent(HtmlPrintActivity.this, WebViewActivity.class);
                intent.putExtra(WebViewActivity.INTENT_KEY_URL, totalList.get(position).getHtmlUrl());
                intent.putExtra(WebViewActivity.INTENT_KEY_TITLE, totalList.get(position).getHtmlName());
                startActivity(intent);
            } else {
                DialogPlus dialog = DialogPlus.newDialog(HtmlPrintActivity.this)
                        .setContentHeight(DensityUtil.dip2px(300))
//                            .setAdapter(adapter)
                        .setGravity(Gravity.CENTER)
                        .setCancelable(true)
                        .setContentHolder(new ViewHolder(R.layout.dialog_layout))
                        .setExpanded(true)  // This will enable the expand feature, (similar to android L share dialog)
                        .create();
                dialog.show();

                View view1 = dialog.getHolderView();
                EditText etAddress = view1.findViewById(R.id.et_address);
                EditText etName = view1.findViewById(R.id.et_name);
                TextView tvCancel = view1.findViewById(R.id.tv_cancel);
                tvCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                TextView tvOk = view1.findViewById(R.id.tv_ok);
                tvOk.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        LogUtil.i("点击确定");
                        x.task().run(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    DbManager db = x.getDb(DbUtils.daoConfig);

                                    HtmlCollectTable htmlCollectTable = new HtmlCollectTable();
                                    htmlCollectTable.setHtmlName("" + etName.getText().toString().trim());
                                    htmlCollectTable.setHtmlUrl("" + etAddress.getText().toString().trim());
                                    htmlCollectTable.setHtmlImage(R.mipmap.moren);
                                    db.saveOrUpdate(htmlCollectTable);

                                    List<HtmlCollectTable> htmlCollectTableList = db.selector(HtmlCollectTable.class).findAll();
                                    if (htmlCollectTableList != null) {
                                        totalList.clear();
                                        htmlCollectTableList.add(setDefaultAdd());
                                        totalList.addAll(htmlCollectTableList);
                                    }
                                    LogUtil.i("total list size is : " + totalList.toString());
                                } catch (DbException e) {
                                    e.printStackTrace();
                                    LogUtil.e("增加错误 ： " + e.getMessage());
                                }

                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        htmlCollectAdapter.notifyDataSetChanged();
                                        dialog.dismiss();
                                    }
                                });

                            }
                        });

                    }
                });
            }
        });

        gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                LogUtil.i("按下的data是 : " + totalList.get(position).getHtmlName());

                LogUtil.i("按下的position是 : " + position);
                if (!TextUtils.equals(totalList.get(position).getHtmlName(),htmlCollect[0]) || !TextUtils.equals(totalList.get(position).getHtmlName(),tempValue)){
                    AlertDialog.Builder builder = new AlertDialog.Builder(HtmlPrintActivity.this).setIcon(R.mipmap.ic_launcher).setTitle("是否删除收藏?")
                            .setMessage("您确定要删除吗").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    //ToDo: 你想做的事情
                                    x.task().run(new Runnable() {
                                        @Override
                                        public void run() {
                                            try {
                                                DbManager db = x.getDb(DbUtils.daoConfig);

                                                List<HtmlCollectTable> htmlCollectTableList = db.selector(HtmlCollectTable.class).findAll();
                                                if (htmlCollectTableList != null) {
                                                    totalList.clear();

                                                    db.delete(htmlCollectTableList.get(position));
                                                    htmlCollectTableList.remove(htmlCollectTableList.get(position));

                                                    htmlCollectTableList.add(setDefaultAdd());
                                                    totalList.addAll(htmlCollectTableList);
                                                }
                                                LogUtil.i("total list size is : " + totalList.toString());
                                            } catch (DbException e) {
                                                e.printStackTrace();
                                                LogUtil.e("增加错误 ： " + e.getMessage());
                                            }

                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    htmlCollectAdapter.notifyDataSetChanged();
                                                    dialogInterface.dismiss();
                                                }
                                            });

                                        }
                                    });
                                }
                            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    //ToDo: 你想做的事情
                                    dialogInterface.dismiss();
                                }
                            });
                    builder.create().show();

                }else {
                    return false;
                }
                return true;
            }
        });
    }

    TextView.OnEditorActionListener onEditorActionListener = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                LogUtil.i("监听到回车键或搜索键");
                String etUrl = et_url.getText().toString().trim();

                Intent intent = new Intent(HtmlPrintActivity.this, WebViewActivity.class);
                intent.putExtra(WebViewActivity.INTENT_KEY_URL, etUrl);
//                intent.putExtra(WebViewActivity.INTENT_KEY_TITLE, totalList.get(position).getHtmlName());
                startActivity(intent);
            }

            return false;
        }
    };

    private HtmlCollectTable setDefaultAdd() {
        HtmlCollectTable htmlCollectBean = new HtmlCollectTable();
        htmlCollectBean.setHtmlName(tempValue);
        htmlCollectBean.setHtmlImage(R.mipmap.tianjia);
        return htmlCollectBean;
    }


    @Override
    public int getLayoutId() {
        return R.layout.activity_html_print;
    }
}